//
//  ZLTabBarRoot.swift
//  ZLNavigationRoot
//
//  Created by KDWL on 2023/1/9.
//

import UIKit

public class ZLTabBarRoot: UITabBarController {
    /// 子控制器
    public var navcs: [ZLNavigationRoot] = []
    /// 底部tabbar背景图
    public lazy var backgroundImageView: UIImageView = {
        let imageView = UIImageView()
        imageView.contentMode = .scaleAspectFill
        return imageView
    }()
    
    public override func viewDidLoad() {
        super.viewDidLoad()
        self.tabBar.backgroundColor = UIColor.white
        self.tabBar.insertSubview(self.backgroundImageView, at: 0)
        self.backgroundImageView.snp.makeConstraints { make in
            make.edges.equalTo(UIEdgeInsets.zero)
        }
    }
    /// 添加子控制器
    public func addItem(button: UIButton, viewController: ZLBaseViewController) {
        let navc = ZLNavigationRoot(rootViewController: viewController)
        self.navcs.append(navc)
        viewControllers = self.navcs
        guard let item = self.tabBar.items?.last else { return }
        item.image = button.image(for: .normal)
        item.selectedImage = button.image(for: .selected)
        item.title = button.titleLabel?.text
        UITabBarItem.appearance().setTitleTextAttributes([.font: button.titleLabel?.font as Any, .foregroundColor: button.titleColor(for: .normal) as Any], for: UIControlState.normal)
        UITabBarItem.appearance().setTitleTextAttributes([.font: button.titleLabel?.font as Any, .foregroundColor: button.titleColor(for: .selected) as Any], for: UIControlState.selected)
    }
    /// 隐藏tabbar
    public func hiddenTabBar(animated: Bool = false) {
        if !animated {
            self.tabBar.isHidden = true
            return
        }
        UIView.animate(withDuration: 0.15, delay: 0, options: .curveEaseIn) {
            var frame = self.tabBar.frame
            frame.origin.y = self.view.frame.size.height
            self.tabBar.frame = frame
        } completion: { result in
            self.tabBar.isHidden = true
        }
    }
    /// 隐藏tabbar
    public func showTabBar(animated: Bool = false) {
        if !animated {
            self.tabBar.isHidden = false
            return
        }
        self.tabBar.isHidden = false
        UIView.animate(withDuration: 0.15, delay: 0, options: .curveEaseOut) {
            var frame = self.tabBar.frame
            frame.origin.y = self.view.frame.size.height - frame.size.height
            self.tabBar.frame = frame
        }
    }
    
    public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
